/* ************************************************************************

   Copyright:

   License:

   Authors: SALMON Charles

************************************************************************ */

/* ************************************************************************

#asset(bip/*)
#asset(thirdparty/jsonrpc.js)
#asset(qx/icon/Tango/32/*)
#asset(qx/icon/Tango/16/*)
#asset(qx/icon/Tango/22/*)
#asset(qx/icon/Tango/48/*)


************************************************************************ */

/**
 * This is the main application class of your custom application "bip"
 */
qx.Class.define("bip.Application",
{
  extend : qx.application.Standalone,
  
  events :
  {
    /**
     * Data event fired after the model has been created. The data will be the
     * created model.
     */
    "loaded" : "qx.event.type.Data",

    /**
     * Fired when an error (aborted, timeout or failed) occurred
     * during the load. If you want more details, use the {@link #changeState}
     * event.
     */
    "error" : "qx.event.type.Event"
  },
  
  properties :
  {
    
    state : {
      check : [
        "configured", "queued", "sending", "receiving",
        "completed", "aborted", "timeout", "failed"
      ],
      init : "configured",
      event : "changeState"
    }
  },

  /*
  *****************************************************************************
     MEMBERS
  *****************************************************************************
  */

  members :
  {
  	__effect : null,
    __container : null,
    __okButton : null,
    __nameField : null,
    __passwordField : null,
    
    __prepareEffect : function()
    {
      this.__effect = new qx.fx.effect.combination.Shake(this.__container.getContainerElement().getDomElement());
    },
    
    /**
     * Login to the application, called on login button press
     */
    login : function(evt)
    {
    	// create the request
      this.__request = new qx.io.remote.Request("j_security_check", "POST");
      this.__request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      this.__request.setParameter("j_username", this.__nameField.getValue());
      this.__request.setParameter("j_password", this.__passwordField.getValue());
      // register the internal even before the user has the change to
      // register its own event in the delegate
      this.__request.addListener(
        "completed", this.__loginCompleteHandler, this
      );
      
      // mapp the state to its own state
      this.__request.addListener("changeState", function(ev) {
        var state = ev.getData();
        this.setState(state);
        if (state === "failed" || state === "aborted" || state === "timeout") {
        	alert("Connection error, please try again "+state);
          this.fireEvent("error");
        }
      }, this);
      
      this.__request.send();
    	/*alert(this.__nameField.getValue()+" "+this.__passwordField.getValue());
      this.__effect.start();*/
    },
    
    /**
     * Handler for the completion of the login request
     *
     * @param ev {qx.io.remote.Response} The event fired by the request.
     */
    __loginCompleteHandler : function(ev)
    {
       var data = ev.getContent();
       if (data.search(/LOGIN_ERROR/i) > 0) {
      	 alert("Wrong username/password");
       } else {
      	 this.adminView();
       }
       
       // fire complete event
       //this.fireDataEvent("loaded", this.getModel());
    },

    /**
     * This method contains the initial application code and gets called 
     * during startup of the application
     * 
     * @lint ignoreDeprecated(alert)
     */
    main : function()
    {
      // Call super class
      this.base(arguments);

      // Enable logging in debug variant
      if ((qx.core.Environment.get("qx.debug")))
      {
        // support native logging capabilities, e.g. Firebug for Firefox
        qx.log.appender.Native;
        // support additional cross-browser console. Press F7 to toggle visibility
        qx.log.appender.Console;
        var username = "dev";
      	this.adminView();
      	return;
      }

      /*
      -------------------------------------------------------------------------
        Below is your actual application code...
      -------------------------------------------------------------------------
      */
      
      try {
      	var username = USERNAME;
      	this.adminView();
        	
      } catch(e) {
      	// Login
      	
      	/* Container layout */
        var layout = new qx.ui.layout.Grid(9, 5);
        layout.setColumnAlign(0, "right", "top");
        layout.setColumnAlign(2, "right", "top");

        /* Container widget */
        this.__container = new qx.ui.groupbox.GroupBox().set({
          contentPadding: [16, 16, 16, 16]
        });
        this.__container.setLayout(layout);

        this.__container.addListener("resize", function(e)
        {
          var bounds = this.__container.getBounds();
          this.__container.set({
            marginTop: Math.round(-bounds.height / 2),
            marginLeft : Math.round(-bounds.width / 2)
          });
        }, this);

        this.getRoot().add(this.__container, {left: "50%", top: "30%"});

        /* Labels */
        var labels = ["Name", "Password"];
        for (var i=0; i<labels.length; i++) {
          this.__container.add(new qx.ui.basic.Label(labels[i]).set({
            allowShrinkX: false,
            paddingTop: 3
          }), {row: i, column : 0});
        }

        /* Text fields */
        this.__nameField = new qx.ui.form.TextField();
        this.__passwordField = new qx.ui.form.PasswordField();

        this.__container.add(this.__nameField.set({
          allowShrinkX: false,
          paddingTop: 3
        }), {row: 0, column : 1});

        this.__container.add(this.__passwordField.set({
          allowShrinkX: false,
          paddingTop: 3
        }), {row: 1, column : 1});

        /* Button */
        var button1 = this.__okButton =  new qx.ui.form.Button("Login");
        button1.setAllowStretchX(false);

        this.__container.add(
          button1,
          {
            row : 3,
            column : 1
          }
        );

        /* Check input on click */
        button1.addListener("execute", this.login, this);
        
        /* Prepare effect as soon as the container is ready */
        this.__container.addListener("appear", this.__prepareEffect, this);
      	
      }
    },
    
    mainView: function() {
    	alert("main");
    	qx.io.PartLoader.require(["main"],function() {
    			var main = new bip.MainView();
    			this.getRoot().add(main, {edge:0});
    	},this);
    },
    
    adminView: function() {
    	qx.io.PartLoader.require(["admin"],function() {
    			var main = new bip.AdminView();
    			try {
    				this.getRoot().remove(this.__container);
    			} catch(e) {}
    			this.getRoot().add(main, {edge:0});
    	},this);
    }
  },

  /*
   *****************************************************************************
      DESTRUCTOR
   *****************************************************************************
   */

  destruct : function()
  {
    this._disposeObjects("__container", "__okButton", "__effect","__nameField","__passwordField");
  }

});
